﻿using Core.CSV;
using Prism.Ioc;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;

namespace Core.Log
{
    public class Notify
    {
        private event Action<string> eventHandlerNotify;
        /// <summary>
        /// 使用事件属性
        /// </summary>
        public event Action<string> EventHandlerNotify
        {
            add { eventHandlerNotify = value; }
            remove { eventHandlerNotify -= value; }
        }

        private IContainerExtension _extension;
        private CSVDataHelper dataSave = new CSVDataHelper();

        /// <summary>
        /// 区域名称
        /// </summary>
        public string Area { get; set; }

        //数据有效期
        public int HowManyDays { get; set; } = 7;

        public Notify(string Area)
        {
            _extension = ContainerLocator.Current;
            dataSave.FileFolder = "Log";
            this.Area = Area;
            dataSave.Supplement = Area;
            dataSave.HowManyDays = HowManyDays;
            dataSave.Title = "时间,内容";
            dataSave.Init();
        }

        /// <summary>
        /// 轮询方式的数据队列
        /// </summary>
        private ConcurrentQueue<string> DataQueue = new ConcurrentQueue<string>();

        /// <summary>
        /// 添加提示信息
        /// </summary>
        /// <param name="area">类型</param>
        /// <param name="msg">内容</param>
        public void Add(string msg)
        {
            string args = string.Format("{0} {1}", DateTime.Now.ToString("HH:mm:ss.ffff"), msg);
            //开始处理
            if (eventHandlerNotify != null)
            {
                //如果有缓存数据则 则先处理完缓存数据
                while (DataQueue.Count() > 0)
                {
                    string result;
                    DataQueue.TryDequeue(out result);
                    eventHandlerNotify(result);
                    Thread.Sleep(1);
                }
                eventHandlerNotify(args);
            }
            SaveData(args);
        }

        private void SaveData(string args)
        {
            try
            {
                dataSave.Save(args);
            }
            catch (Exception ex)
            {
            }
        }

    }
}
